﻿using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SPVisualDev.Services
{
    public class IIS
    {
        public static void RecycleIISAppPool(string Url)
        {
            if (string.IsNullOrEmpty(Url))
            {
                using (DirectoryEntry de = new DirectoryEntry("IIS://localhost/W3SVC/AppPools"))
                {
                    foreach (DirectoryEntry deChild in de.Children)
                    {
                        if (deChild.SchemaClassName == "IIsApplicationPool")
                        {
                            int state = (int)deChild.Properties["AppPoolState"].Value;
                            if (state == 2)
                            {
                                deChild.Invoke("Recycle");
                            }
                        }
                    }
                }
            }
            else
            {
                SPWebApplication webapp = SPWebApplication.Lookup(new Uri(Url));
                if (webapp == null)
                    throw new Exception("Web application " + Url + " could not be found.");

                using (DirectoryEntry de = new DirectoryEntry("IIS://localhost/W3SVC/AppPools"))
                {
                    foreach (DirectoryEntry deChild in de.Children)
                    {
                        if (deChild.SchemaClassName == "IIsApplicationPool" && deChild.Name == webapp.ApplicationPool.Name)
                        {
                            int state = (int)deChild.Properties["AppPoolState"].Value;
                            if (state == 2)
                            {
                                deChild.Invoke("Recycle");
                            }
                        }
                    }
                }
            }
        }
    }
}
